<template>
  <div class="comment-container">
    <h1>发表评论</h1>
    <hr>
    <textarea placeholder="请输入评论" maxlength="120" v-model="commentContent"></textarea>
    <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>
    <div class="comment-list">
      <div class="comment-item" v-for="(cmt,i) in commentList" :key="i">
        <div class="comment-title">
          <span>第{{i}}楼</span>
          <span>{{cmt.userName}}</span>
          <span>发表时间:{{cmt.addTime}}</span>
        </div>
        <div class="comment-content">{{cmt.content}}</div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click="getNextPage">更多评论</mt-button>
  </div>
</template>
<style lang="less" scoped>
.comment-container {
  textarea {
    margin-bottom: 0px;
  }
  .comment-list {
    font-size: 14px;
    .comment-item {
      margin-top: 5px;
      .comment-title {
        background-color: #aaa;
      }
      .comment-content {
        padding: 10px;
      }
    }
  }
}
</style>
<script>
import { Toast } from "mint-ui";
import Interface from "../../interface.js";
export default {
  data() {
    return {
      commentContent: "",
      pageIndex: 1,
      commentList: []
    };
  },
  props: ["id", "type"],
  created() {
    // 创建时ajax请求评论列表
    this.getComment();
  },
  methods: {
    getNextPage() {
      this.pageIndex++;
      this.getComment();
    },
    getComment() {
      this.axios
        .get(
          Interface.getcommentsBaseUrl +
            this.id +
            "?pageindex=" +
            this.pageIndex +
            "&type=" +
            this.type
        )
        .then(data => {
          if (data.data.status == true) {
            this.commentList = this.commentList.concat(data.data.message);
          } else {
            alert("后台数据异常");
          }
        })
        .catch(err => {
          alert(err.message);
        });
    },
    postComment() {
      var vue = this
      this.axios.post(Interface.postcommentBaseUrl+this.id,{
        type:this.type,
        content:this.commentContent
      })
        .then(data => {
          if (data.data.status === true) {
            Toast("发表成功");
            this.commentList.unshift({
              addTime: new Date(),
              userName: "匿名用户",
              content: vue.commentContent
            });
            this.commentContent = "";
          } else {
            Toast("获取数据出错了");
          }
        })
        .catch(err => {
          Toast(err.message);
        });
    }
  }
};
</script>
